// Copyright 2006 - Ricardo Stuven (rstuven@gmail.com)
//
// This file is part of MsSqlSpatial.
// MsSqlSpatial is free software; you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
// 
// MsSqlSpatial is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Lesser General Public License for more details.

// You should have received a copy of the GNU Lesser General Public License
// along with MsSqlSpatial; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA 

using System;
using System.IO;
using System.Data;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using Microsoft.SqlServer.Server;
using MsSqlSpatial;
using System.Collections.Generic;

namespace MsSqlSpatial
{
	/// <summary>
	/// Helper class for aggregate functions.
	/// </summary>
	internal static class Aggregate<T>
	{
		private static readonly Dictionary<string, T> cache = new Dictionary<string, T>();

		public static void Initialize(out string key, out T aggregate)
		{
			key = Guid.NewGuid().ToString();
			if (typeof(T).IsInterface || typeof(T).IsValueType)
			{
				aggregate = default(T);
			}
			else
			{
				aggregate = Activator.CreateInstance<T>();
			}
			cache[key] = aggregate;
		}

		public static T Terminate(string cacheKey)
		{
			T aggregate = cache[cacheKey];
			cache.Remove(cacheKey);
			return aggregate;
		}

		public static void Read(BinaryReader r, out string key, out T aggregate)
		{
			key = r.ReadString();
			aggregate = cache[key];
		}

		public static void Write(BinaryWriter w, string key, T aggregate)
		{
			w.Write(key);
			cache[key] = aggregate;
		}
	}
}